using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;
using Castle.ActiveRecord.Framework.Config;

namespace Demo.Model.Utils
{
    public class SessionScopeWebModule : IHttpModule
    {
        public static bool CommitError
        {
            get
            {
                if ((HttpContext.Current == null) || (HttpContext.Current.Items["commiterror"] == null))
                    return false;
                else
                    return (bool)HttpContext.Current.Items["commiterror"];
            }
            set
            {
                if (HttpContext.Current != null)
                    HttpContext.Current.Items["commiterror"] = value;
            }
        }

        // In the Init function, register for HttpApplication 
        // events by adding your handlers.
        public void Init(HttpApplication application)
        {
            application.BeginRequest += new EventHandler(this.Application_BeginRequest);
            application.EndRequest += new EventHandler(this.Application_EndRequest);
        }

        public void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Items.Add("sessionscope", new SessionScope());
        }

        public void Application_EndRequest(object sender, EventArgs e)
        {
            try
            {
                SessionScope scope = HttpContext.Current.Items["sessionscope"] as SessionScope;

                if (scope != null)
                {
                    scope.Dispose(CommitError);
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Trace.Warn("Error", "EndRequest: " + ex.Message, ex);
            }
        }

        #region IHttpModule Members

        public void Dispose()
        {
        }

        #endregion
    }
}